﻿using UnityEngine;
using System.Collections;

public class MovingPlatform : MonoBehaviour 
{

	public	float 		moveSpeed		= 	2.0f;
	private	int			direccion		=	1;

	/*
	// Use this for initialization
	void Start () 
	{

	}
	*/

	void Update()
	{

		Vector3 mov = Vector3.right * this.direccion * this.moveSpeed * Time.deltaTime;
		//---*Mueve la plataforma Movil segun la velocidad y direccion:
		this.transform.Translate(mov);

		//---*Calcula los puntos supIzq y infDer del rect que forma el boxCollider2D de este GameObject:
		//---*Punto A o esquina supIzq:
		Vector3 pointA = this.gameObject.transform.position;
		pointA.x -= this.gameObject.GetComponent<BoxCollider2D>().size.x /2.0f;
		pointA.y -= this.gameObject.GetComponent<BoxCollider2D>().size.y /2.0f;
		//---*Punto B o esquina infDer:
		Vector3 pointB = this.gameObject.transform.position;
		pointB.x += this.gameObject.GetComponent<BoxCollider2D>().size.x /2.0f;
		pointB.y += this.gameObject.GetComponent<BoxCollider2D>().size.y /2.0f;
		//---*Vemos si en base a estos 2 puntos hay overlap con algo del layer "Ground":		
		Collider2D[] cols =Physics2D.OverlapAreaAll(pointA,pointB,1<<LayerMask.NameToLayer("Ground"));
		//---*Si "toca" con algo del layer "Ground":
		if(cols.Length>0)
		{
			//---*Cambia la direccion de movimiento:
			this.direccion *= -1;
			//---*Ajusta un poco la posicion en base al proximo step:
			this.gameObject.transform.Translate(mov*-1);
		}

	}



}
